package chainmaker

import (
	"crypto/tls"
	"errors"
	"net/http"
	"time"

	"chainmaker.org/chainmaker/smarteditor/conf"

	"github.com/parnurzeal/gorequest"
)

func GetRemoteUserInfo(baseInfoUrl, token string) (*RespUserInfo, error) {
	userInfo := &RespUserInfo{}

	response, data, err := gorequest.New().
		TLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
		Get(baseInfoUrl).
		AppendHeader("Authorization", "Bearer "+token).
		Timeout(60 * time.Second).
		EndStruct(userInfo)

	if nil != err || http.StatusOK != response.StatusCode {
		log.Errorf("[GetRemoteUserInfo] get user info failed: %+v, %s", err, data)
		return nil, errors.New("get user info failed")
	}

	return userInfo, nil
}

func Logout(baseInfoUrl, token, refreshToken string) error {
	log.Infof("[logout] baseInfoUrl=%s token=%s refreshToken=%s", baseInfoUrl, token, refreshToken)
	data := make(map[string]string, 0)
	data["client_id"] = conf.Wide.ChainMakerClientId
	data["client_secret"] = conf.Wide.ChainMakerClientSecret
	data["refresh_token"] = refreshToken

	resp, body, err := gorequest.New().
		TLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
		Post(baseInfoUrl).
		Type("urlencoded").
		AppendHeader("Authorization", "Bearer "+token).
		AppendHeader("Content-Type", "application/x-www-form-urlencoded").
		SendMap(data).
		Timeout(5 * time.Second).
		End()

	if err != nil && len(err) > 0 {
		log.Errorf("[Logout]  failed \nresp: %+v \nbody: %+v \nerr: %+v", resp, body, err)
		return err[0]
	}
	return nil
}
